package com.study.www.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.study.www.test1.entity.User;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author : 89007337.zhuyanpeng
 * @date :Create in  2019/8/19- 11:51
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "test1EntityManagerFactory",
        transactionManagerRef = "test1TransactionManager",
        basePackages = {Test1JpaConfig.PACKAGES}
)
public class Test1JpaConfig {

    public static final String PACKAGES="com.study.www.test1";


    @Bean("test1DataSource")
    @Primary
    @ConfigurationProperties("spring.datasource.db1")
    public DataSource dateSource(){
        //return DataSourceBuilder.create().build();
        return  DruidDataSourceBuilder.create().build();
    }



    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean test1EntityManagerFactory(EntityManagerFactoryBuilder builder){
        return builder
                .dataSource(dateSource())
                .packages(PACKAGES)
                .build();
    }
    //PlatformTransactionManager核心事务管理器,是Spring的事务管理器核心接口。
    //Spring本身并不支持事务实现，只是负责包装底层事务，应用底层支持什么样的事务策略，Spring就支持什么样的事务策略。

    @Bean
    @Primary
    PlatformTransactionManager test1TransactionManager(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(test1EntityManagerFactory(builder).getObject());
    }
}
